package me.xuym.crawler.t66y;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.network.HttpClient;
import com.cbs.java.component.network.Request;
import com.cbs.java.component.network.Response;
import com.cbs.java.component.network.decoder.TextDecoder;
import me.xuym.crawler.Processor;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by broche on 10/09/2017.
 */
public class T66yDownloadUrlConvertor extends Processor<List<T66yResult>, List<T66yFullResult>> {
    private HttpClient httpClient;

    public T66yDownloadUrlConvertor(Application application) {
        super(application);

        HttpClient.Builder builder = new HttpClient.Builder();
        String proxyHost = "cephei.xuym.me";
        int proxyPort = 1010;
        builder.getOkBuilder().proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)));

        if (proxyHost != null && !proxyHost.equals("")) {
            builder.getOkBuilder().proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)));
        }
        httpClient = builder.build();
    }

    @Override
    protected List<T66yFullResult> onProcess(List<T66yResult> t66yResults) throws Exception {
        List<T66yFullResult> results = new ArrayList<>();
        for (T66yResult result : t66yResults) {
            Request request = new Request("http://t66y.com/" + result.getUrl()).setDecoder(new TextDecoder("gbk"));
            Response response = httpClient.sendSync(request);
            String content = (String) response.getResult();
            Pattern pattern = Pattern.compile("http://(www.)?rmdown.com/link.php\\?hash=([A-Za-z0-9]*)");
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                result.setTorrent(matcher.group(2));
                results.add(new T66yFullResult(result));
            }
        }
        return results;
    }
}
